<?php

/**
 * 会员中心
 */
namespace User\Controller;
use Common\Controller\MemberbaseController;
class ProfileController extends MemberbaseController {
	
	protected $users_model;
	function _initialize(){
		parent::_initialize();
		$this->users_model=M("User");
	}
	
    //编辑用户资料
	public function edit() {
		$userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
		$this->assign($user);
    	$this->display();
    }
    
    public function edit_post() {
    	if(IS_POST){
    		$userid=sp_get_current_userid();
    		$_POST['id']=$userid;
    		if ($this->users_model->create()) {
				if ($this->users_model->save()!==false) {
					$user=$this->users_model->find($userid);
					sp_update_current_user($user);
					$this->success("保存成功！",U("user/profile/edit"));
				} else {
					$this->error("保存失败！");
				}
			} else {
				$this->error($this->users_model->getError());
			}
    	}
    	
    }
    
    public function password() {
    	$userid=sp_get_current_userid();
    	$user=$this->users_model->where(array("id"=>$userid))->find();
    	$this->assign($user);
    	$this->display();
    }
    
    public function password_post() {
    	if (IS_POST) {
    		if(empty($_POST['old_password'])){
    			$this->error("原始密码不能为空！");
    		}
    		if(empty($_POST['password'])){
    			$this->error("新密码不能为空！");
    		}
    		$uid=sp_get_current_userid();
    		$admin=$this->users_model->where("id=$uid")->find();
    		$old_password=$_POST['old_password'];
    		$password=$_POST['password'];
    		if(sp_password($old_password)==$admin['user_pass']){
    			if($_POST['password']==$_POST['repassword']){
    				if($admin['user_pass']==sp_password($password)){
    					$this->error("新密码不能和原始密码相同！");
    				}else{
    					$data['user_pass']=sp_password($password);
    					$data['id']=$uid;
    					$r=$this->users_model->save($data);
    					if ($r!==false) {
    						$this->success("修改成功！");
    					} else {
    						$this->error("修改失败！");
    					}
    				}
    			}else{
    				$this->error("密码输入不一致！");
    			}
    	
    		}else{
    			$this->error("原始密码不正确！");
    		}
    	}
    	 
    }
    
    
    function bangs(){
    	$oauth_user_model=M("OauthUser");
    	$uid=sp_get_current_userid();
    	$oauths=$oauth_user_model->where(array("uid"=>$uid))->select();
    	$new_oauths=array();
    	foreach ($oauths as $oa){
    		$new_oauths[strtolower($oa['from'])]=$oa;
    	}
    	$this->assign("oauths",$new_oauths);
    	$this->display();
    }
    
    function avatar(){
    	$userid=sp_get_current_userid();
		$user=$this->users_model->where(array("id"=>$userid))->find();
		$this->assign($user);
    	$this->display();
    }
    
    function avatar_upload(){
    	$config=array(
    			'FILE_UPLOAD_TYPE' => sp_is_sae()?"Sae":'Local',//TODO 其它存储类型暂不考虑
    			'rootPath' => './'.C("UPLOADPATH"),
    			'savePath' => './avatar/',
    			'maxSize' => 512000,//500K
    			'saveName'   =>    array('uniqid',''),
    			'exts'       =>    array('jpg', 'png', 'jpeg'),
    			'autoSub'    =>    false,
    	);
    	$upload = new \Think\Upload($config);//
    	$info=$upload->upload();
    	//开始上传
    	if ($info) {
    	//上传成功
    	//写入附件数据库信息
    		$first=array_shift($info);
    		$file=$first['savename'];
    		$_SESSION['avatar']=$file;
    		$this->ajaxReturn(sp_ajax_return(array("file"=>$file),"上传成功！",1),"AJAX_UPLOAD");
    	} else {
    		//上传失败，返回错误
    		$this->ajaxReturn(sp_ajax_return(array(),$upload->getError(),0),"AJAX_UPLOAD");
    	}
    }
    
    function avatar_update(){
    	if(!empty($_SESSION['avatar'])){
    		$targ_w = intval($_POST['w']);
    		$targ_h = intval($_POST['h']);
    		$x = $_POST['x'];
    		$y = $_POST['y'];
    		$jpeg_quality = 90;
    		
    		$avatar=$_SESSION['avatar'];
    		$avatar_dir=C("UPLOADPATH")."avatar/";
    		if(sp_is_sae()){//TODO 其它存储类型暂不考虑
    			$src=C("TMPL_PARSE_STRING.__UPLOAD__")."avatar/$avatar";
    		}else{
    			$src = $avatar_dir.$avatar;
    		}
    		
    		$avatar_path=$avatar_dir.$avatar;
    		
    		
    		if(sp_is_sae()){//TODO 其它存储类型暂不考虑
    			$img_data = sp_file_read($avatar_path);
    			$img = new \SaeImage();
    			$size=$img->getImageAttr();
    			$lx=$x/$size[0];
            	$rx=$x/$size[0]+$targ_w/$size[0];
            	$ty=$y/$size[1];
            	$by=$y/$size[1]+$targ_h/$size[1];
    			
    			$img->crop($lx, $rx,$ty,$by);
    			$img_content=$img->exec('png');
    			sp_file_write($avatar_dir.$avatar, $img_content);
    		}else{
    			$image = new \Think\Image();
    			$image->open($src);
    			$image->crop($targ_w, $targ_h,$x,$y);
    			$image->save($src);
    		}
    		
    		$userid=sp_get_current_userid();
    		$result=$this->users_model->where(array("id"=>$userid))->save(array("avatar"=>$avatar));
    		$_SESSION['user']['avatar']=$avatar;
    		if($result){
    			$this->success("头像更新成功！");
    		}else{
    			$this->error("头像更新失败！");
    		}
    		
    	}
    }
    //微信公众号管理
    public function  pubWeChat()
    {

    	$pubwechat=M("pubwechat");
    	$where["uid"]=get_current_userid();
    
    	$pwbList=$pubwechat->where($where)->select();
    	$this->assign("pwblist",$pwbList);
  		$this->assign("status",array("正在审核","审核失败","审核成功"));
    	$this->display("pubwechat");
    } 
    //添加公众号
    public function addPubWec()
    {
    	if(IS_POST)
    	{
    		
    		$pubwechat=M("pubwechat");
    		if($_SESSION["user"]["user_type"]==2)
    		{				
    			$rules = array(
    				//array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
    				array('pwc_name', 'require', '公众号名称必须填写！', 1 ),
    				array('pwc_id','require','公众号id必须填写！',1), 
    				
    				array('wechatArticle','require','公众号发布的文章必须填写！',1),
    			//	array('wechatArticle','URL','公众号发布的文章格式不正确！',1),
    				array('pwc_fsnum','require','粉丝数必须填写！',1),
    				array('pwc_fsnum','number','粉丝数必须位数字！',1),
    				array('pwc_tx','require','请上传头像图片！',1),
    				array('pwc_ewm','require','请上传公众号的二维码！',1),
    				array('pwc_fs','require','请上传粉丝截图！',1)
    				);
    		}else{
    			$rules = array(
    					array('pwc_name', 'require', '公众号名称必须填写！', 1 ),
    					array('pwc_id','require','公众号id必须填写！',1),
    					array('wechatArticle','require','公众号发布的文章必须填写！',1),
    				//	array('wechatArticle','URL','公众号发布的文章格式不正确！',1),
    					array('pwc_tx','require','请上传头像图片！',1),
    					array('pwc_ewm','require','请上传公众号的二维码！',1)
    				);
    				
    			
    		}
    		if($pubwechat->validate($rules)->create()===false)
    		{
    			$this->error($pubwechat->getError());
    		}else{
    			$pubwechat->uid=get_current_userid();
    			$pubwechat->status=0;
    			$pubwechat->posttime=time();
    			$pubwechat->add();
    			$this->success("提交成功，等待管理员审核",U('user/profile/pubWeChat'));
    		}	
    	}
    	
    	$this->display("addpubwec");	
    }
    //添加微信号
    public function WeChat()
    {
        $this->UserCreatErCodeTime("del");
    	$uid=sp_get_current_userid();
    	$where["uid"]=$uid;
    	$welist=M("wechatNumber")->alias("W")->join("__USER__ as U on U.id=W.uid")->where($where)->select();
    		
    	$this->assign("welist",$welist);
    	$this->assign("status",array("正在认证","认证失败","通过认证"));
    	$this->display("wechat");	
    }
    /*
     * 生成绑定二维码
     * 
     * */
    public function  creatErcode()
    {
       $creatTime=$this->UserCreatErCodeTime("add");   
       $options=get_site_options();
       $uid=sp_get_current_userid();
       $text=$options["site_host"]."/index.php/user/Auth/wechat/uid/".$uid."/creattime/".$creatTime;
       $fileurl="./".C("UPLOADPATH")."/userErCode/userweChatAuto_".$uid.".png";
       creatErCodeImg($text,$fileurl);
       $this->success($fileurl);
    }
    /*
     * 向用户表添加时间戳判断用户是否存在绑定行为
     * 
     * */
    private  function UserCreatErCodeTime($act="del")
    {
      $user=M("User"); 
      $where["id"]=sp_get_current_userid();
        if($act=="add")
        {
            $data['creattime']=time();   
        }elseif($act=="del")
        {
            $data['creattime']="";
        }elseif($act=="get")
        {
           $result=$user->where($where)->find();
            return $result["creattime"];
        }
        $user->where($where)->save($data);
        return  $data['creattime'];
    }
    /*
     * 获取状态信息
     * */
    public function getStatus()
    {
         $status=$this->UserCreatErCodeTime("get"); 
         if(empty($status))
         {
             $this->success($status);
         }else{
             $this->error("未绑定");
         }
    }
    function updateImg(){

    	$result=uploadImg();
    	if($result["status"])
    	{
    		$this->ajaxReturn(sp_ajax_return(array("file"=>$result["file"]),"上传成功！",1),"AJAX_UPLOAD");
    	}else{
    		$this->ajaxReturn(sp_ajax_return(array(),$result["msg"],0),"AJAX_UPLOAD");
    	}
    }
    /**
     *  生成二维码实例 
     *  $text=$options["site_host"]."/index.php/user/Auth/wechat/uid/".$uid;
    	$fileurl="./".C("UPLOADPATH")."/userErCode/userweChatAuto_".$uid.".png";
    	//$touxiang="./".C("UPLOADPATH")."/avatar/55157e973b69b.png";
    	if(!file_exists($fileurl))
    	{
    		creatErCodeImg($text,$fileurl);
    	}
    	//添加带头像的二维码
    	//creatErCoDeImgHeader($text,$fileurl,$touxiang);
     * 
     * 
     * 
     * */

    /*
     * 朋友圈认证申请 
     */
   public function friendAuth()
   {
   		$wid=I("get.wid",0,"intval");
   		$info=$this->getwechatInfo($wid);
   		if($info['status']==2){ $this->error("朋友圈认证已通过");}
		if(IS_POST)
		{
			$wechatn=M("wechatNumber");
			$_POST["status"]=0;
			$data=$wechatn->create();
			$result=$wechatn->where("wid=$wid")->save($data);
			if($result){ $this->success("提交成功，请耐心等待审核",U("user/profile/WeChat"));}else{
				$this->error("添加失败");
			}
			
		}
   		
   		$this->assign($info); 
		$this->assign("circle",$this->getCircle());  	
   		$this->display();
   }
   
   /*
    * 获取微信信息
    * */
   protected function getwechatInfo($wid)
   {
   	 $where["wid"]=$wid;	
   	 $info=M("wechatNumber")->where($where)->find();
   	if(!$info)$this->error("不存在当前信息");
   	return $info;
   }
   /*
    * 获取圈子信息
    * */
   protected function getCircle()
   {
    return 	M("CircleType")->order("listorder desc")->getField("id,t_name");
   }
   
   
   
   
   
   
    
    
}
    
